package ArrayPackage2;

/**
 * @author Lzm
 * @version 1.0
 */
public class generateMatrix_ {
  public static void main(String[] args) {
    int[][] matrix = generateMatrix(3);

  }

  public static int[][] generateMatrix(int n) {
    // 1. 定义动态边界
    int startX = 0;
    int startY = 0;
    // 2. 定义循环次数
    int loop= 0;
    // 3. 定义坐标
    int x = 0;
    int y = 0;
    int num = 1;
    int[][] result = new int[n][n];
    while(loop <= n / 2){
      for(y = startY ; y < n - startY - 1; y++){
        result[startX][y] = num++;
      }
      for (x = startX ; x < n - startX - 1; x++){
        result[x][y] = num++;
      }
      for ( ; y > startY ; y--){
        result[x][y] = num++;
      }
      for ( ; x > startX ; x--){
        result[x][y] = num++;
      }
      loop++;
      startX++;
      startY++;
    }
    if (n % 2 != 0){
      result[x][y] = num;
    }
    return result;
  }
}
